/**
 * 
 */
package neptune.web.client.view;

import com.google.gwt.user.client.ui.Composite;

/**
 * A class that represents a View in an application organized following the MVC
 * pattern. View implements the interface HasHistoryToken to manage views
 * switching through history tokens.<br/><br/>
 * 
 * The HistoryToken is set with the method setToken() and is considered also the
 * View's name. Every View has also a prefix to its History token. This prefix
 * is used to build views gerarchies. You can define a SuperView, a View that
 * can contain other Views, and so you can define a View gerarchy.<br/> To
 * understand witch View has to be shown, you can use the gerarchy. The gerarchy
 * is encoded in the token string used with the GWT History management
 * framework.
 * 
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * @see neptune.web.client.view.HasHistoryToken
 * @see neptune.web.client.view.SuperView
 * 
 */
public class View extends Composite implements HasHistoryToken, HasState {

	// This view prefix
	private String prefix = "";
	// The view name
	private String name = "";

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.HasHistoryToken#getPrefix()
	 */
	public String getPrefix() {
		return prefix;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.HasHistoryToken#getToken()
	 */
	public String getToken() {
		return HistoryTokenUtils.buildToken(prefix, name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.HasHistoryToken#setPrefix(java.lang.String)
	 */
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	
	public void setName(String name) throws DuplicatedTokenException {
		// If this view was already registerd with another token, before
		// registering
		// the new one, the older is unregistered
		if (!this.name.equals(""))
			HistoryTokenUtils.unregisterViewToken(this.name);

		HistoryTokenUtils.registerViewToken(name);
		this.name = name;
	}
	
	public void unsetToken(){
		HistoryTokenUtils.unregisterViewToken(name);
		name = "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.HasHistoryToken#getToken(java.lang.String)
	 */
	public String getToken(String stateId) {
		return HistoryTokenUtils.buildToken(prefix, name, stateId);
	}

	/**
	 * Returns this View name, that is the view token, without prefix or state
	 * indications.
	 * 
	 * @return
	 */
	public String getName() {
		return this.name;
	}

	public String encodeState() {
		return null;
	}

	public void setState(String encodedStateString) {
		
	}

	/* (non-Javadoc)
	 * @see com.google.gwt.user.client.ui.UIObject#toString()
	 */
	@Override
	public String toString() {
		return name;
	}
	
	
}
